import decimal
import random
import time

import requests

from orderSharing.retailOrderSharing import RetailOrderSharing


class ActivitySnapUp:

    relationshipChain = {}

    def __init__(self):
        self.retailOrderSharing = RetailOrderSharing()

    # 预期升级、换绑结果
    def only_find_superior_users(self, originalUserId, userId, userLevel):
        self.retailOrderSharing.session.commit()
        referee_user = self.retailOrderSharing.session.execute(
            "select ru1.referee_user_id, ru2.share_num\
                     from retail_users ru1\
                     inner join retail_users ru2 on ru1.referee_user_id = ru2.user_id\
                     where ru1.user_id = :userId limit 1",
            params={"userId": userId}).first()

        self.retailOrderSharing.session.commit()
        user_vip = self.retailOrderSharing.session.execute(
                "select vip_level from retail_vips where user_id = :userId limit 1",
                params={"userId": referee_user[0]}).first()

        if user_vip == None:
            self.only_find_superior_users(originalUserId, referee_user[0], userLevel)
        else:
            if userLevel < user_vip[0]:
                self.relationshipChain[originalUserId] = (referee_user[0], user_vip[0], referee_user[1], userLevel, 0)

            if userLevel == user_vip[0]:
                if userLevel >= 3:
                    self.relationshipChain[originalUserId] = (
                    referee_user[0], user_vip[0], referee_user[1], userLevel, 0)
                else:
                    self.retailOrderSharing.session.commit()
                    share_num = self.retailOrderSharing.session.execute(
                        "select ru.share_num, rvl.share_num\
                                from retail_users ru\
                                inner join retail_vips rv on ru.user_id = rv.user_id\
                                inner join retail_vip_levels rvl on rvl.vip_level = rv.vip_level+1\
                                where ru.user_id = :userId limit 1",
                        params={"userId": referee_user[0]}).first()

                    if share_num != None:
                        if share_num[0] + 1 >= share_num[1]:
                            self.relationshipChain[originalUserId] = (
                            referee_user[0], user_vip[0] + 1, 0, userLevel, 0)

                            self.only_find_superior_users(referee_user[0], referee_user[0], user_vip[0] + 1)
                        else:
                            self.relationshipChain[originalUserId] = (
                            referee_user[0], user_vip[0], share_num[0] + 1, userLevel, 0)

            if userLevel > user_vip[0]:
                self.only_find_superior_users(originalUserId, referee_user[0], userLevel)

    # 核对升级、换绑
    def check_the_superior_user(self, userId):

        self.retailOrderSharing.session.commit()
        referee_user = self.retailOrderSharing.session.execute(
            "select ru1.referee_user_id, ru2.share_num, rv.vip_level, ru1.share_num\
                     from retail_users ru1\
                     inner join retail_users ru2 on ru1.referee_user_id = ru2.user_id\
                     inner join retail_vips rv on rv.user_id = ru1.user_id\
                     where ru1.user_id = :userId limit 1",
            params={"userId": userId}).first()
        print("referee_user：", referee_user)

        self.retailOrderSharing.session.commit()
        user_vip = self.retailOrderSharing.session.execute(
            "select vip_level from retail_vips where user_id = :userId limit 1",
            params={"userId": referee_user[0]}).first()

        if user_vip != None:
            if userId in self.relationshipChain:
                print("升级换绑》》》referee_user：", referee_user, user_vip)

                if self.relationshipChain[userId][4] != referee_user[3]:
                    print(
                        "自身推荐会员数错误{}，预期：{}，实际：{}".format(userId, self.relationshipChain[userId][4], referee_user[3]))

                if self.relationshipChain[userId][3] != referee_user[2]:
                    print(
                        "自身升级错误{}，预期：{}，实际：{}".format(userId, self.relationshipChain[userId][3], referee_user[2]))

                if self.relationshipChain[userId][0] != referee_user[0]:
                    print(
                        "升级换绑错误{}，预期：{}，实际：{}".format(userId, self.relationshipChain[userId][0], referee_user[0]))

                if self.relationshipChain[userId][1] != user_vip[0]:
                    print(
                        "购买vip订单{}，上级达到指标升级，级别错误，预期：{}，实际：{}".format(userId, self.relationshipChain[userId][1],
                                                                     user_vip[0]))

                if self.relationshipChain[userId][2] != referee_user[1]:
                    print(
                        "购买vip订单{}，上级推荐会员数量错误，预期：{}，实际：{}".format(userId, self.relationshipChain[userId][2],
                                                                  referee_user[1]))

            self.check_the_superior_user(referee_user[0])

    # 今日必抢退款、分润、赠送会员升级核对
    def today_must_rob(self):

        activityList = requests.request("GET",
                                        url="https://test.api.vodeshop.com/api/retail/activity/group/goods/second-level-activity-list/3?limit=9999&page=1",
                                        headers={"x-request-from": "web", "x-requested-with": "XMLHttpRequest",
                                                 "authorization":"Bearer "}).json()["data"]["data"]
        for i in range(0, len(activityList) - 1):
            if activityList[i]["price"] == "0.00" or activityList[i]["activity_type"] == 4:
                activityList.pop(i)

        activityIndex = random.randint(0, len(activityList) - 1)
        activity = activityList[activityIndex]
        print("activity：", activity)

        activityDetail = requests.request("GET",
                                        url="https://test.api.vodeshop.com/api/retail/activity/show/"+str(activity["id"]),
                                        headers={"x-request-from": "web", "x-requested-with": "XMLHttpRequest",
                                                 "authorization": "Bearer "}).json()["data"]
        activitySku = activityDetail["activity_goods"]["retail_activity_goods_sku"][0]
        print("activitySku：", activitySku)

        self.retailOrderSharing.session.commit()
        retail_activity_goods_skus = self.retailOrderSharing.session.execute(
            "select rag.round_number, rags.cost_price, rags.price, rags.platform_profit_price, rag.retail_vip_level_id, rag.subsidy_methods, rag.subsidy_rules, rags.activity_subsidy_money\
                     from retail_activity_goods rag\
                     inner join retail_activity_goods_skus rags on rag.id = rags.retail_activity_goods_id\
                     where rag.id = :activityId",
            params={"activityId": activity["id"]}).first()

        self.retailOrderSharing.session.commit()
        spikes = self.retailOrderSharing.session.execute(
            "select count(id) from retail_activity_spikes where pay_status = 1 and retail_activity_goods_id = :activityId",
            params={"activityId": activity["id"]}).first()

        self.retailOrderSharing.session.commit()
        userList = self.retailOrderSharing.session.execute("select ru.user_id, u.mobile, ua.id, ru.bind_retail_store_id, ru.current_retail_store_id\
                                            from retail_users ru\
                                            inner join user_addresses ua on ru.user_id = ua.user_id\
                                            inner join users u on u.id = ru.user_id\
                                            where ru.is_real_name = 1 and ua.is_default = 1\
                                            and ru.user_id not in (select ras.user_id from retail_activity_spikes ras\
                                            where ras.retail_activity_goods_id = :activityId and ras.pay_status = 1) order by ru.created_at desc", params={"activityId": activity["id"]}).fetchall()

        self.retailOrderSharing.session.commit()
        retail_sets = self.retailOrderSharing.session.execute(
            "select credit_ratio, bind_store_ratio, current_store_ratio, agent_ratio from retail_sets limit 1").first()

        subRatioList = []
        for num in range(1, 3):
            self.retailOrderSharing.session.commit()
            sub_ratio = self.retailOrderSharing.session.execute(
                "select sub_ratio from retail_vip_levels where vip_level = :vipLevel limit 1",
                params={"vipLevel": num}).first()
            subRatioList.append(sub_ratio[0])

        # 设置100%中奖（中奖人数=抽奖人数）
        for user in userList[:(spikes[0] // retail_activity_goods_skus[0] + 1) * retail_activity_goods_skus[0] - spikes[0]]:

            self.retailOrderSharing.session.commit()
            vip_level = self.retailOrderSharing.session.execute(
                "select vip_level from retail_vips where user_id = :userId limit 1",
                params={"userId": user[0]}).first()
            print("vip_level：", vip_level)

            if vip_level == None:
                self.only_find_superior_users(user[0], user[0], retail_activity_goods_skus[4])
            else:
                if vip_level[0] < retail_activity_goods_skus[4]:
                    self.only_find_superior_users(user[0], user[0], retail_activity_goods_skus[4])

                elif vip_level[0] == retail_activity_goods_skus[4]:

                    self.retailOrderSharing.session.commit()
                    share_num = self.retailOrderSharing.session.execute(
                        "select ru.share_num, rvl.share_num\
                                from retail_users ru\
                                inner join retail_vips rv on ru.user_id = rv.user_id\
                                inner join retail_vip_levels rvl on rvl.vip_level = rv.vip_level+1\
                                where ru.user_id = :userId limit 1",
                        params={"userId": user[0]}).first()

                    if share_num != None:
                        if share_num[0] + 1 >= share_num[1]:
                            self.only_find_superior_users(user[0], user[0], vip_level[0] + 1)

                        else:
                            self.retailOrderSharing.session.commit()
                            referee_user = self.retailOrderSharing.session.execute(
                                "select ru1.referee_user_id, ru2.share_num\
                                         from retail_users ru1\
                                         inner join retail_users ru2 on ru1.referee_user_id = ru2.user_id\
                                         where ru1.user_id = :userId limit 1",
                                params={"userId": user[0]}).first()

                            self.retailOrderSharing.session.commit()
                            user_vip = self.retailOrderSharing.session.execute(
                                "select vip_level from retail_vips where user_id = :userId limit 1",
                                params={"userId": referee_user[0]}).first()

                            self.relationshipChain[user[0]] = (
                                referee_user[0], user_vip[0], referee_user[1], vip_level[0], share_num[0] + 1)

        creationTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

        newUserList = []
        for u in userList[:(spikes[0] // retail_activity_goods_skus[0] + 1) * retail_activity_goods_skus[0] - spikes[0]]:
            user = [u[0], u[1], u[2], u[3], u[4]]
            newUserList.append(user)

        placeUserList = []
        for user in newUserList:

            self.retailOrderSharing.session.commit()
            vip_level = self.retailOrderSharing.session.execute(
                "select vip_level from retail_vips where user_id = :userId limit 1",
                params={"userId": user[0]}).first()
            print("vip_level：", vip_level)

            requests.request("POST", url="https://test.api.vodeshop.com/api/sms/user-login", json={"mobile": user[1]})
            time.sleep(5)

            print("user：", user)
            userToken = requests.request("POST", url="https://test.api.vodeshop.com/api/auth/login/mobile",
                                         json={"mobile": user[1], "password": "", "code": "111111"}).json()
            print("userToken：", userToken)
            token = userToken["data"]["token_type"] + " " + userToken["data"]["access_token"]

            againActivityList = requests.request("GET",
                                            url="https://test.api.vodeshop.com/api/retail/activity/group/goods/second-level-activity-list/3?limit=9999&page=1",
                                            headers={"x-request-from": "web", "x-requested-with": "XMLHttpRequest",
                                                     "authorization": token}).json()["data"]["data"]
            for i in range(0, len(againActivityList) - 1):
                if againActivityList[i]["price"] == "0.00" or againActivityList[i]["activity_type"] == 4:
                    againActivityList.pop(i)

            againActivity = againActivityList[activityIndex]

            orderCheck = requests.request("POST", url="https://test.api.vodeshop.com/api/retail/check-order",
                                          headers={"x-request-from": "web", "x-requested-with": "XMLHttpRequest",
                                                   "authorization": token},
                                          json={"retail_goods_id": [activityDetail["id"]], "address_id": user[2]}).json()
            confirm = requests.request("POST", url="https://test.api.vodeshop.com/api/retail/activity/order/confirm",
                                       headers={"x-request-from": "web", "x-requested-with": "XMLHttpRequest",
                                                "authorization": token},
                                       json={"activity_goods_id":activity["id"],"activity_goods_sku_id":activitySku["id"],"quantity":1,"address_id":user[2]}).json()
            activity_goods_sku = confirm["data"]["goods"][0]["items"][0]["goods_sku"]
            original_amount = decimal.Decimal(activity_goods_sku["price"]) + decimal.Decimal(
                orderCheck["data"][0]["addr_carriage"]) - decimal.Decimal(str(activity_goods_sku["sub_price"]))
            print("original_amount：", original_amount)

            if vip_level != None:
                proportion = 0

                if vip_level[0] == 1:
                    proportion = subRatioList[0]

                elif vip_level[0] == 2:
                    proportion = subRatioList[1]

                elif vip_level[0] == 3:
                    proportion = 100 - retail_sets[3]

                if decimal.Decimal(againActivity["sub_price"]) != (
                        retail_activity_goods_skus[2] - retail_activity_goods_skus[1] - retail_activity_goods_skus[3] - retail_activity_goods_skus[7]) * \
                        proportion / 100:
                    print("{}今日必抢活动列表会员立减错误，预期{}，实际{}".format(activity["id"],
                                                          (retail_activity_goods_skus[2] - retail_activity_goods_skus[1] - retail_activity_goods_skus[3] - retail_activity_goods_skus[7]) *
                                                          proportion / 100, decimal.Decimal(againActivity["sub_price"])))

                if decimal.Decimal(str(confirm["data"]["sub_price"])) != (
                        retail_activity_goods_skus[2] - retail_activity_goods_skus[1] - retail_activity_goods_skus[3] - retail_activity_goods_skus[7]) * proportion / 100:
                    print("{}结算页面会员立减错误，预期{}，实际{}".format(activity["id"], (
                            retail_activity_goods_skus[2] - retail_activity_goods_skus[1] - retail_activity_goods_skus[3] - retail_activity_goods_skus[7]) * proportion / 100,
                                                          decimal.Decimal(str(confirm["data"]["sub_price"]))))

            activityOrder = requests.request("POST", url="https://test.api.vodeshop.com/api/retail/activity/spike/order",
                                     headers={"x-request-from": "web", "x-requested-with": "XMLHttpRequest",
                                              "authorization": token},
                                     json={"activity_goods_id":activity["id"],"activity_goods_sku_id":activitySku["id"],"quantity":1,"address_id":user[2],"group_id":None,"pay_type":1}).json()

            time.sleep(2)
            self.retailOrderSharing.session.commit()
            order_sn = self.retailOrderSharing.session.execute(
                "select order_sn, id from payments where user_id = :userId and targetable_id =:targetableId order by created_at desc limit 1",
                params={"userId": user[0], "targetableId": activityOrder["data"]["order_id"]}).first()
            print("order_sn：", order_sn)

            payment = requests.request("POST", url="https://test.api.vodeshop.com/api/v2/test/notifyyyy",
                                   data={"out_trade_no": order_sn[0], "trade_no": order_sn[0],
                                         "total_amount": "1"}).json()
            print("payment：", payment)

            if activityOrder["code"] == 0 and payment["code"] == 0:
                user.append(activityOrder["data"]["order_id"])
                user.append(decimal.Decimal(orderCheck["data"][0]["addr_carriage"]))
                user.append(vip_level)
                user.append(order_sn[1])
                user.append(original_amount)
                placeUserList.append(user)

        time.sleep(300)

        self.retailOrderSharing.session.commit()
        user_id_list = self.retailOrderSharing.session.execute(
            "select ro.user_id from\
                    retail_activity_spikes ras\
                    inner join retail_orders ro on ro.id = ras.retail_order_id\
                    where ras.retail_activity_goods_id = :activityId and ro.created_at > :creation",
            params={"activityId": activity["id"], "creation":creationTime}).fetchall()

        cumulativeSubsidy = 0.00

        for placeUser in placeUserList:
            if (placeUser[0], ) in user_id_list:

                crossStore = False
                self.retailOrderSharing.session.commit()
                retail_store_id = self.retailOrderSharing.session.execute(
                    "select ro.retail_store_id, rog.id\
                            from retail_orders ro\
                            inner join retail_order_goods rog on rog.retail_order_id = ro.id\
                            inner join retail_activity_spikes ras on ras.retail_order_id = ro.id\
                            where ras.id = :spikeOrderId limit 1",
                    params={"spikeOrderId": placeUser[5]}).first()

                union, partner = 1, 1
                if placeUser[7] != None:
                    if placeUser[7][0] == 1:
                        union += 1
                    elif placeUser[7][0] == 2:
                        partner += 1

                self.retailOrderSharing.check_members_sharing(placeUser[0], retail_store_id[1], placeUser[9], subRatioList,
                                           retail_activity_goods_skus[2] - retail_activity_goods_skus[1] - retail_activity_goods_skus[3] - retail_activity_goods_skus[7],
                                           retail_sets, 1, union, partner, crossStore, placeUser[3], retail_store_id[0], placeUser[7])

                # 设置100%中奖（中奖人数=抽奖人数）
                self.check_the_superior_user(placeUser[0])

            else:
                self.retailOrderSharing.session.commit()
                refund_amount = self.retailOrderSharing.session.execute(
                    "select price from payment_refunds where payment_id = :paymentId",
                    params={"paymentId": placeUser[8]}).first()
                if refund_amount == None:
                    print("{}未中奖退款错误，预期{}，实际{}".format(placeUser[5], placeUser[9], refund_amount))
                else:
                    if refund_amount[0] != placeUser[9]:
                        print("{}未中奖退款错误，预期{}，实际{}".format(placeUser[5], placeUser[9],refund_amount[0]))

                self.retailOrderSharing.session.commit()
                change_price = self.retailOrderSharing.session.execute(
                    "select change_price from retail_user_price12_records where user_id = :userId and target_id = :targetId",
                    params={"userId": placeUser[0], "targetId": placeUser[5]}).first()

                if retail_activity_goods_skus[5] == 1:
                    if retail_activity_goods_skus[6] == 1:
                        if change_price[0] != retail_activity_goods_skus[7] / (retail_activity_goods_skus[0] - len(user_id_list)):
                            print("{}未中奖平均补贴错误，预期{}，实际{}".format(placeUser[5], retail_activity_goods_skus[7] / (retail_activity_goods_skus[0] - len(user_id_list)), change_price[0]))
                    elif retail_activity_goods_skus[6] == 2:
                        cumulativeSubsidy += change_price[0]

        if retail_activity_goods_skus[6] == 2:
            if cumulativeSubsidy != retail_activity_goods_skus[7]:
                print("{}随机补贴合计错误，预期{}，实际{}".format(activity["id"], cumulativeSubsidy,
                                                      retail_activity_goods_skus[7]))


if __name__ == "__main__":
    ActivitySnapUp().today_must_rob()
    print("relationshipChain：", ActivitySnapUp.relationshipChain)